<template>
	<view class="yp">
		<app-headers></app-headers>
		<!-- #ifdef H5 -->
		<view class="paddtb20"></view>
		<!-- #endif -->
		<view class="paddlr30">
			<text class="cuIcon-back" @click="back"></text>
		</view>
		<view class="wrap">

			<view class="key-input">
				<view class="title">输入验证码</view>
				<view class="tips">验证码已发送至 + {{this.account}}</view>
				<uMessageInput ref='uMessageInput' :focus="true" :value.sync="value" @change="change" @finish="finish" mode="bottomLine"
				 :maxlength="maxlength"></uMessageInput>
				<text :class="{ error: error }">验证码错误，请重新输入</text>
				<view class="captcha">
					<text :class="{ noCaptcha: show }" @tap="noCaptcha">收不到验证码点这里</text>
					<text :class="{ regain: !show }">{{ second }}秒后重新获取验证码</text>
				</view>
			</view>

		</view>
	</view>

</template>

<script>
	// MD5加密
	import MD5 from '@/common/Tools/md5.js'
	import {
		API$login,
		API$getSMSInterface,
		API$CheckVerCode,
	} from '../../../common/API/other.js';
	import {
		API$GetUserinfo
	} from '../../../common/API/home.js';
	import uMessageInput from '../../../common/components/u-message-input/u-message-input.vue'

	let timers = null // 防抖
	export default {
		components: {
			uMessageInput
		},
		data() {
			return {
				maxlength: 6,
				value: '',		// 短信验证码
				second: 60,
				show: false,
				error: false,


				account: "", // 页面带参 账号
				optTyPe: "" // 页面带参 验证类作用类型
			};
		},
		computed: {},
		onLoad(opt) {
			this.account = opt.account
			this.optTyPe = opt.type

			this.getSMS(this.account)  // 加载页面获取验证码
			let interval = setInterval(() => {
				this.second--;
				if (this.second <= 0) {
					this.show = true;
					clearInterval(interval);
				}
			}, 1000);
		},
		methods: {
			// 收不到验证码选择时的选择
			noCaptcha() {
				uni.showActionSheet({
					itemList: ['重新获取验证码', '注册账号'],
					success: (res) => {
						if (res.tapIndex === 0) {
							if (timers) return

							this.getSMS(this.account) // 获取验证码
							this.show = false;
							this.second = 60
							timers = setInterval(() => {
								this.second--;
								if (this.second <= 0) {
									this.show = true;
									clearInterval(timers);
								}
							}, 1000);
						}
						if (res.tapIndex === 1) {
							this.$pub.redirTo('/pages/other/register/index')
						}
					},
					fail: function(res) {

					}
				});
			},
			// change事件侦听
			change(value) {
				console.log('change', value);
			},
			// 输入完验证码最后一位执行
			 async finish(value) {
				console.log('finish', value);


				if (this.optTyPe === 'ResetPwd') {
					console.log(this.optTyPe)
					let {code,msg} = await API$CheckVerCode({verCode:value,account:this.account})
					this.$pub.Toast(msg)
					if(code===200){
						this.$pub.naviTo(`/pages/other/ResetPwd/ResetPwd?account=${this.account}&&verCode=${this.value}`)		
					}
				} else {
					this.Logins({
						account: this.account,
						verCode: value
					})
				}


			},
			back() {
				this.$pub.back()
			},
			/****************************************************数据接口部分**************************************************************************/
			// 获取短信验证码
			async getSMS(account) {
				let {
					code,
					msg
				} = await API$getSMSInterface({
					SMSType: this.optTyPe === 'ResetPwd' ? "ResetPwd" : "login",
					account
				})
				console.log(code, msg)
			},
			// 登录/重置密码
			async Logins(Json) {
				uni.showLoading({
					mask: true
				});
				let {
					code,
					msg,
					Token,
					Sts
				} = await API$login(Json)
				uni.hideLoading();
				console.log(code, msg)
				if (code === 204) {
					this.error = true;
					this.$refs.uMessageInput.ClearInputValue()
				}
				this.$pub.Toast(msg);
				if (code === 200) {
					this.$pub.setStorageSync('Token', Token);
					this.$pub.setStorageSync('Sts', Sts);
					let res1 = await API$GetUserinfo();
					if (res1.code == 200) {
						this.$pub.setStorageSync('UserInfo', res1.result);
						
						
						// 取账号缓存
						let oldAccountList = this.$pub.getStorageSync('AcclountList')
						let indexS = oldAccountList ? oldAccountList.findIndex(i => i._id === res1.result._id) : -1
						// 账号缓存不存在
						if (!oldAccountList || indexS === -1) {
							oldAccountList = oldAccountList ? oldAccountList :[],
							oldAccountList ? oldAccountList.forEach(i=>i.IsCheck=false) :""
							let AccontJson = [{
								UpdateDate: new Date(),
								Token: Token,
								IsCheck:true ,// 当前选中的登录的账号
								Account: res1.result.account,
								Nickname: res1.result.Nickname,
								Avatar: res1.result.avatar,
								_id: res1.result._id,
								
								Info:res1.result
							}]
							this.$pub.setStorageSync('AcclountList', [...oldAccountList,...AccontJson]); // 添加账号缓存
						// 账号缓存存在 覆盖掉旧数据
						} else {
							oldAccountList.forEach(i=>i.IsCheck=false)
							
							console.warn('我是覆盖的逻辑', oldAccountList, oldAccountList[indexS])
							oldAccountList[indexS].UpdateDate = new Date();
							oldAccountList[indexS].Token = Token;
							oldAccountList[indexS].Nickname = res1.result.Nickname;
							oldAccountList[indexS].Avatar = res1.result.avatar;
							oldAccountList[indexS].IsCheck = true;
							
							oldAccountList[indexS].Info = res1.result;
							this.$pub.setStorageSync('AcclountList', [...oldAccountList]); // 添加账号缓存
						}
						
						
						
						// 登录环信IM
						// 环信IM登录
						try{
						    this.$HuanxinIM.close()
						}catch(e){
						    console.log('初始化登录IM',e)
						}finally{
						    setTimeout(async()=>{
						        console.log('登录IM')
						        // 登录IM
						        let {msg,IM_data} = await this.$HuanxinIM.Login({
						            user:res1.result._id,
						            pwd: MD5(res1.result.pwd)
						        })
						        if(msg==='fail'){
						            this.$pub.Toast('账号密码错误~',IM_data)
						            this.$pub.reLaunch('/pages/other/login/index')
						        }
						        console.log(IM_data)
						        this.$pub.setStorageSync('HuanXinInfo',IM_data)
						    },2500)
						}
						
						
					}
					this.$pub.swiTab('/pages/index/index');
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 80rpx;
	}

	.box {
		margin: 30rpx 0;
		font-size: 30rpx;
		color: 555;
	}

	.key-input {
		padding: 30rpx 0;

		text {
			display: none;
		}

		.error {
			display: block;
			color: red;
			font-size: 30rpx;
			margin: 20rpx 0;
		}
	}

	.title {
		font-size: 50rpx;
		color: #333;
	}

	.key-input .tips {
		font-size: 30rpx;
		color: #333;
		margin-top: 20rpx;
		margin-bottom: 60rpx;
	}

	.captcha {
		color: $u-type-warning;
		font-size: 30rpx;
		margin-top: 40rpx;

		.noCaptcha {
			display: block;
		}

		.regain {
			display: block;
		}
	}
</style>
